from flask import request
from flask_shop.menu import menu,menu_api
from flask_shop import models,db
from flask_restful import Resource
from flask_shop.utils.message import to_dict_msg
from flask_cors import *

class Menu(Resource):
    def get(self):
        menu_list = []
        type_ = request.args.get("type")
        if type_ == "list":
            # 获取数据，并将数据填充到menu_listli
            mu = models.Menu.query.filter(models.Menu.level != 0).all()
            for m in mu:
                menu_list.append(m.to_dict())
        else:
            mu = models.Menu.query.filter(models.Menu.level == 1).all()
            for m in mu:
                # 获取一级菜单并转成json
                first_mu = m.to_dict()
                # 创建二级菜单容器
                first_mu["children"] = []
                for sm in m.children:
                    #获取二级菜单并换成json
                    secd_dict = sm.to_dict()
                    # 在二级菜单里创建三级菜单容器，并添加3级菜单数据
                    secd_dict["children"] = sm.get_child_list()
                    # 吧二级菜单添加到1级的children列表中
                    first_mu["children"].append(secd_dict)
                # 把一级菜单加到根列表中
                menu_list.append(first_mu)
        return to_dict_msg(200,data=menu_list)

menu_api.add_resource(Menu,"/menu")
